<template>
  <view class="attendance-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="header-title">课程签到</text>
    </view>

    <!-- 课程信息卡片 -->
    <view class="course-card">
      <view class="course-header">
        <text class="course-name">{{ courseInfo.courseName }}</text>
        <text class="course-time">{{ courseInfo.time }}</text>
      </view>
      <view class="course-details">
        <view class="detail-item">
          <text class="detail-label">📍</text>
          <text class="detail-value">{{ courseInfo.location }}</text>
        </view>
        <view class="detail-item">
          <text class="detail-label">🎨</text>
          <text class="detail-value">{{ courseInfo.className }}</text>
        </view>
      </view>
    </view>

    <!-- 签到统计信息 -->
    <view class="sign-in-summary">
      <view class="summary-item">
        <text class="summary-label">已签到</text>
        <text class="summary-value signed">{{ signInSummary.signedCount }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">未签到</text>
        <text class="summary-value not-signed">{{ signInSummary.notSignedCount }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">总人数</text>
        <text class="summary-value total">{{ students.length }}</text>
      </view>
    </view>

    <!-- 签到操作按钮 -->
    <view class="sign-in-actions">
      <button class="action-button primary" @click="handleBatchSignIn">
        批量签到
      </button>
      <button class="action-button secondary" @click="handleRefresh">
        刷新状态
      </button>
    </view>

    <!-- 学生列表 -->
    <view class="student-list">
      <view class="list-header">
        <text class="header-text">学生姓名</text>
        <text class="header-text">签到状态</text>
        <text class="header-text">操作</text>
      </view>
      
      <view class="student-item" v-for="student in students" :key="student.id">
        <view class="student-info">
          <text class="student-name">{{ student.name }}</text>
        </view>
        <view class="student-status">
          <text :class="['status-tag', student.signed ? 'signed' : 'not-signed']">
            {{ student.signed ? '已签到' : '未签到' }}
          </text>
          <text class="sign-time" v-if="student.signInTime">{{ student.signInTime }}</text>
        </view>
        <view class="student-action">
          <button 
            class="sign-button" 
            :class="student.signed ? 'disabled' : ''" 
            @click="handleSingleSignIn(student)" 
            :disabled="!canSignIn || student.signed"
          >
            {{ student.signed ? '已签到' : '签到' }}
          </button>
        </view>
      </view>
      
      <view class="empty-list" v-if="students.length === 0">
        <text class="empty-text">暂无学生数据</text>
      </view>
    </view>

    <!-- 批量签到确认弹窗 -->
    <uni-popup ref="batchSignInPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">批量签到确认</text>
        </view>
        <view class="popup-body">
          <text class="popup-text">确定要为所有未签到的学生进行批量签到吗？</text>
          <text class="popup-count">共 {{ notSignedStudents.length }} 名学生未签到</text>
        </view>
        <view class="popup-footer">
          <button class="popup-button cancel" @click="closeBatchSignInPopup">取消</button>
          <button class="popup-button confirm" @click="confirmBatchSignIn">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import request from '@/utils/request'
  // 日期工具函数
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  export default {
    data() {
    return {
      // 课程ID
      courseId: '',
      // 班级ID
      classId: '',
      // 课程排序
      sort: '',
      // 课程信息
      courseInfo: {
        courseName: '',
        time: '',
        location: '',
        className: ''
      },
      // 学生列表
      students: [],
      // 签到统计
      signInSummary: {
        signedCount: 0,
        notSignedCount: 0
      },
      // 是否可以签到
      canSignIn: true,
      // 未签到学生列表
      notSignedStudents: [],
      // 定时器
      checkSignInTimer: null
    }
  },
    onLoad(options) {
      // 获取课程ID和其他参数
      this.courseId = options.courseId
      this.classId = options.classId
      this.sort = options.sort
      this.courseInfo.courseName = options.courseName || ''
      this.courseInfo.time = options.time || ''
      this.courseInfo.location = options.location || ''
      this.courseInfo.className = options.className || ''
      
      // 加载学生列表和签到记录
      this.loadCourseStudents()
      // 检查是否可以签到
      this.checkCanSignIn()
    },
    onShow() {
      // 页面显示时再次检查
      this.checkCanSignIn()
      // 设置定时器，每分钟检查一次
      this.checkSignInTimer = setInterval(() => {
        this.checkCanSignIn()
      }, 60000)
    },
    onUnload() {
      // 页面卸载时清除定时器
      if (this.checkSignInTimer) {
        clearInterval(this.checkSignInTimer)
        this.checkSignInTimer = null
      }
    },
    computed: {
      // 计算未签到学生数量
      notSignedCount() {
        return this.students.filter(student => !student.signed).length
      }
    },
    methods: {
      // 检查是否可以签到
      checkCanSignIn() {
        if (!this.courseInfo.time) {
          this.canSignIn = false
          return
        }
        
        // 解析课程时间，支持格式：14:00 ~ 15:00 或 14:00-15:00
        const timeStr = this.courseInfo.time
        const timeRegex = /(\d{2}:\d{2})\s*[-~]\s*(\d{2}:\d{2})/
        const match = timeStr.match(timeRegex)
        
        if (!match || match.length < 3) {
          this.canSignIn = false
          return
        }
        
        const [, startTime, endTime] = match
        
        // 解析开始时间和结束时间
        const [startHour, startMinute] = startTime.split(':').map(Number)
        const [endHour, endMinute] = endTime.split(':').map(Number)
        
        // 获取当前时间
        const now = new Date()
        const currentHour = now.getHours()
        const currentMinute = now.getMinutes()
        
        // 计算总分钟数进行比较
        const startTotalMinutes = startHour * 60 + startMinute
        const endTotalMinutes = endHour * 60 + endMinute
        const currentTotalMinutes = currentHour * 60 + currentMinute
        
        // 判断当前时间是否在课程时间范围内
        this.canSignIn = currentTotalMinutes >= startTotalMinutes && currentTotalMinutes <= endTotalMinutes
      },
      
      // 加载课程学生列表
      loadCourseStudents() {
        request({
          url:`/ysg/work/associatedStudentList?courseId=${this.courseId}`,
          method:'GET'
        }).then(res => {
          if (res.code === 200 && res.rows) {
            this.students = res.rows.map(student => ({
              ...student,
              signed: false,
              signInTime: null
            }))
            // 加载签到记录
            this.loadSignInRecords()
          }
        }).catch(error => {
          console.warn('获取学生列表失败', error)
          // 使用模拟数据
          this.students = [
            { id: 1, name: '张三', signed: false, signInTime: null },
            { id: 2, name: '李四', signed: true, signInTime: '2025-12-02 13:05' },
            { id: 3, name: '王五', signed: false, signInTime: null }
          ]
          this.calculateSignInSummary()
        })
      },
      
      // 加载签到记录
      loadSignInRecords() {
        const data = {
          courseId: this.courseId,
          createTime: formatDate(new Date())
        }
        
        request({
          url:'/ysg/work/getSignInRecords',
          params:data,
          method:'GET'
        }).then(res => {
          if (res.code === 200 && res.rows) {
            const signInMap = new Map()
            res.rows.forEach(record => {
              signInMap.set(record.studentId, record)
            })
            
            // 更新学生签到状态
            this.students.forEach(student => {
              const record = signInMap.get(student.id)
              if (record) {
                student.signed = true
                student.signInTime = record.createTime
              }
            })
            
            // 计算签到统计
            this.calculateSignInSummary()
          }
        }).catch(error => {
          console.warn('获取签到记录失败', error)
        })
      },
      
      // 计算签到统计
      calculateSignInSummary() {
        const signedCount = this.students.filter(student => student.signed).length
        const notSignedCount = this.students.length - signedCount
        
        this.signInSummary = {
          signedCount,
          notSignedCount
        }
        
        // 更新未签到学生列表
        this.notSignedStudents = this.students.filter(student => !student.signed)
      },
      
      // 单个学生签到
      handleSingleSignIn(student) {
        if (!this.canSignIn) {
          this.$modal.msgError('当前不在签到时间段内')
          return
        }
        
        const signInData = {
          studentId: student.id,
          studentName: student.name,
          courseId: this.courseId,
          courseName: this.courseInfo.courseName,
          classId: this.classId,
          className: this.courseInfo.className,
          sort: this.sort
        }
        
        request({
          url:'/ysg/work/signIn',
          data:signInData,
          method:'POST'
        }).then(res => {
          if (res.code === 200) {
            // 更新学生签到状态
            student.signed = true
            student.signInTime = formatDate(new Date())
            // 重新计算签到统计
            this.calculateSignInSummary()
            this.$modalmsgSuccess('签到成功')
          } else {
            this.$modalmsgError('签到失败：' + (res.msg || '未知错误'))
          }
        }).catch(error => {
          console.error('签到请求失败:', error)
          this.$modal.msgError('签到请求失败')
        })
      },
      
      // 批量签到
      handleBatchSignIn() {
        if (!this.canSignIn) {
          this.$modal.msgError('当前不在签到时间段内')
          return
        }
        
        if (this.notSignedStudents.length === 0) {
          this.$modal.msg('所有学生都已签到')
          return
        }
        
        // 显示批量签到确认弹窗
        this.$refs.batchSignInPopup.open()
      },
      
      // 确认批量签到
      confirmBatchSignIn() {
        const signInData = this.notSignedStudents.map(student => ({
          studentId: student.id,
          studentName: student.name,
          courseId: this.courseId,
          courseName: this.courseInfo.courseName,
          classId: this.classId,
          className: this.courseInfo.className,
          sort: this.sort
        }))
        
        request({
          url:'/ysg/work/batchSignIn',
          data:JSON.stringify(signInData),
          method:'POST'
        }).then(res => {
          if (res.code === 200) {
            // 更新所有未签到学生的状态
            this.notSignedStudents.forEach(student => {
              student.signed = true
              student.signInTime = formatDate(new Date())
            })
            // 重新计算签到统计
            this.calculateSignInSummary()
            this.$modal.msgSuccess(`成功为 ${this.notSignedStudents.length} 名学生签到`)
            // 关闭弹窗
            this.closeBatchSignInPopup()
          } else {
            this.$modal.msgError('批量签到失败：' + (res.msg || '未知错误'))
          }
        }).catch(error => {
          console.error('批量签到请求失败:', error)
          this.$modal.msgError('批量签到请求失败')
        })
      },
      
      // 关闭批量签到弹窗
      closeBatchSignInPopup() {
        this.$refs.batchSignInPopup.close()
      },
      
      // 刷新签到状态
      handleRefresh() {
        this.loadSignInRecords()
        this.$modal.msgSuccess('签到状态已刷新')
      }
    }
  }
</script>

<style scoped>
  .attendance-container {
    background-color: #f5f5f5;
    min-height: 100vh;
    padding: 20px;
  }

  /* 页面标题 */
  .page-header {
    text-align: center;
    margin-bottom: 20px;
  }

  .header-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  /* 课程卡片 */
  .course-card {
    background-color: white;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
  }

  .course-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .course-name {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }

  .course-time {
    font-size: 12px;
    color: #666;
    background-color: #f5f7fa;
    padding: 4px 12px;
    border-radius: 15px;
  }

  .course-details {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }

  .detail-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;
  }

  .detail-label {
    margin-right: 8px;
  }

  /* 签到统计 */
  .sign-in-summary {
    background-color: white;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    display: flex;
    justify-content: space-around;
  }

  .summary-item {
    text-align: center;
  }

  .summary-label {
    display: block;
    font-size: 12px;
    color: #666;
    margin-bottom: 5px;
  }

  .summary-value {
    display: block;
    font-size: 20px;
    font-weight: bold;
  }

  .summary-value.signed {
    color: #67c23a;
  }

  .summary-value.not-signed {
    color: #e6a23c;
  }

  .summary-value.total {
    color: #409eff;
  }

  /* 签到操作按钮 */
  .sign-in-actions {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
  }

  .action-button {
    flex: 1;
    height: 45px;
    border: none;
    border-radius: 12px;
    font-size: 14px;
    font-weight: bold;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .action-button.primary {
    background-color: #409eff;
    color: white;
  }

  .action-button.secondary {
    background-color: #67c23a;
    color: white;
  }

  .action-button:disabled {
    background-color: #c0c4cc;
  }

  /* 学生列表 */
  .student-list {
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    padding: 15px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
  }

  .header-text {
    font-size: 14px;
    font-weight: bold;
    color: #333;
    flex: 1;
    text-align: center;
  }

  .student-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
  }

  .student-item:last-child {
    border-bottom: none;
  }

  .student-info {
    flex: 1;
  }

  .student-name {
    font-size: 14px;
    color: #333;
  }

  .student-status {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
  }

  .status-tag {
    font-size: 12px;
    padding: 3px 10px;
    border-radius: 12px;
    font-weight: bold;
  }

  .status-tag.signed {
    background-color: #f0f9eb;
    color: #67c23a;
  }

  .status-tag.not-signed {
    background-color: #fdf6ec;
    color: #e6a23c;
  }

  .sign-time {
    font-size: 10px;
    color: #909399;
  }

  .student-action {
    flex: 1;
    display: flex;
    justify-content: center;
  }

  .sign-button {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 15px;
    font-size: 12px;
    font-weight: bold;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .sign-button.disabled {
    background-color: #c0c4cc;
    color: white;
  }

  /* 空列表 */
  .empty-list {
    padding: 40px 20px;
    text-align: center;
  }

  .empty-text {
    font-size: 14px;
    color: #909399;
  }

  /* 弹窗样式 */
  .popup-content {
    background-color: white;
    border-radius: 12px;
    padding: 20px;
    width: 80%;
    max-width: 400px;
  }

  .popup-header {
    text-align: center;
    margin-bottom: 20px;
  }

  .popup-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  .popup-body {
    text-align: center;
    margin-bottom: 25px;
  }

  .popup-text {
    display: block;
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
  }

  .popup-count {
    display: block;
    font-size: 12px;
    color: #666;
  }

  .popup-footer {
    display: flex;
    gap: 15px;
  }

  .popup-button {
    flex: 1;
    height: 40px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .popup-button.cancel {
    background-color: #f5f7fa;
    color: #606266;
  }

  .popup-button.confirm {
    background-color: #409eff;
    color: white;
  }
</style>